import { ArgumentMetadata, Injectable, PipeTransform, HttpException, HttpStatus } from '@nestjs/common';
import { validate } from 'class-validator'
import { plainToClass } from 'class-transformer'
@Injectable()
export class ValidationPipe implements PipeTransform {
  async transform(value: any, metadata: ArgumentMetadata) {
    console.log('管道----', value);
    console.log('管道----', metadata);
    const { metatype } = metadata
    //如果不存在验证规则,直接返回数据
    if (!metatype || this.toValidate(metatype))
      return value;
    //将对象转换为class来验证
    const object = plainToClass(metatype, value)
    const errors = await validate(object)
    console.log('object', object);
    console.log('errors', errors);

    if (errors.length > 0) {
      const msg = Object.values(errors[0].constraints)[0]
      throw new HttpException(
        {
          message: msg,
          code: 1,
          result:{}
        },
        HttpStatus.OK
      )
    }
    return value
  }
  toValidate(metatype: any): boolean {
    const types = [String, Boolean, Number, Array, Object]
    return types.includes(metatype)
  }
}
